//
//  RotatingViewController.m
//
//  Created by Kenji Hollis on 1/15/09.
//

#import "RotatingViewController.h"
#import <QuartzCore/QuartzCore.h>



@implementation RotatingViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
		portraitViewController = nil;
		landscapeViewController = nil;
    }
    return self;
}

- (void)setPortraitViewController:(UIViewController *)controller {
	portraitViewController = controller;
}

- (void)setLandscapeViewController:(UIViewController *)controller {
	landscapeViewController = controller;
}

- (void)loadView {
	UIView *contentView = [[[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame] autorelease];
	
	[contentView setBackgroundColor:[UIColor clearColor]];
	contentView.autoresizesSubviews = YES;
	self.view = contentView;
	
	[self.view addSubview:portraitViewController.view];
	[self.view addSubview:landscapeViewController.view];
	
	[landscapeViewController.view setHidden:YES];
	[portraitViewController.view setHidden:NO];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	if (portraitViewController != nil) {
		if (interfaceOrientation == UIInterfaceOrientationPortrait ||
			interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) {
			return YES;
		}
	}
	
	if (landscapeViewController != nil) {
		if (interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||
			interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
			return YES;
		}
	}
	
	return NO;
}

- (void)willAnimateFirstHalfOfRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
	[CATransaction begin];
	CATransition *animation = [CATransition animation];
	animation.type = kCATransitionFade;
	animation.duration = duration;
	
	[[self.view layer] addAnimation:animation forKey:@"rotationTransitionFade"];
	
	if (toInterfaceOrientation == UIInterfaceOrientationPortrait ||
		toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) {
		[landscapeViewController.view setHidden:YES];
		[portraitViewController.view setHidden:NO];
	} else {
		[portraitViewController.view setHidden:YES];
		[landscapeViewController.view setHidden:NO];
	}
	
	[CATransaction commit];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}


- (void)dealloc {
    [super dealloc];
}


@end
